CharSequence与String的区别是什么 |
您所在的位置:网站首页 › char 和string的区别 › CharSequence与String的区别是什么 |
CharSequence与String都能用于定义字符串,但CharSequence的值是可读可写序列,而String的值是只读序列。 CharSequence是实现这个接口的实例 举例: CharSequence str = "dd"; 就是 CharSequence str = new String("dd"); CharSequence是封装好的类 这是一个接口,代表的是一个有序字符集合,这个接口包含的方法有:charAt(int index),toString(),length(),subSequence(int start,int end). 这里需要说的一点就是,对于一个抽象类或者是接口类,不能使用new来进行赋值,但是可以通过以下的方式来进行实例的创建: CharSequence cs="hello"; 但是不能这样来创建: CharSequence cs=new CharSequence("hello"); 下面来看看一个例子: TextView tv; //声明一个TextView类型的变量tv CharSequence cs; //声明一个CharSequence类型的变量cs String str; //声明一个字符串类型的str变量 cs=getText(R.string.styled_text); //其实这里使用的this.getText()方法,即指定上下文的方法 tv=(TextView)findViewById(R.id.styled_text); //通过给定的id将tv与对应的组件联系起来 tv.setText(cs); //使用这句代码来设置tv的显示内容 str=getString(R.string.styled_text); tv=(TextView)findViewById(R.id.plain_text); tv.setText(str); Context context=this; //这里使用了Context类型的变量context,指定为当前上下文 Resources res=context.getResources(); //定义一个Resources类型的变量res,并给它赋值 cs=res.getText(R.string.styled_text); //获得R类中指定变量的值 tv=(TextView)findViewById(R.id.styled_text); //同上 tv.setText(cs); //设置值 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |